package com.example.paypallesson01.service;

import com.example.paypallesson01.config.PaypalConfig;
import com.example.paypallesson01.config.PaypalPaymentIntent;
import com.example.paypallesson01.config.PaypalPaymentMethod;
import com.example.paypallesson01.dao.ShopOrderMapper;
import com.example.paypallesson01.model.PaymentEx;
import com.example.paypallesson01.model.ShopOrderItemEx;
import com.example.paypallesson01.model.ShopOrderPayment;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/07/19
 * @Description:
 */
@Service
public class PayDemoService {

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private APIContext apiContext;

    @Autowired
    private ShopOrderPaymentHistoryService shopOrderPaymentHistoryService;

    private static final String CURRENCY = "USD";
    private static final String COMPLETED_STATUS = "completed";


    /**
     * 支付的方法
     * @param paymentEx
     * @param successUrl
     * @param cancelUrl
     * @author: anlu
     * @time: 2021/7/19
     */
    public Payment  createPayment(PaymentEx paymentEx,String successUrl,String cancelUrl)throws Exception{
        Transaction transaction = new Transaction();
        transaction.setDescription(paymentEx.getDescription());
        // 将我们的订单ID保存到支付信息中，用于后面支付回传
        if (null != paymentEx.getOrderId()) {
            transaction.setCustom(paymentEx.getOrderId().toString());
        }
        /**
         * 订单价格
         */
        Amount amount = new Amount();
        amount.setCurrency(CURRENCY);
        // 支付的总价，paypal会校验 total = subTotal + tax + ...
        amount.setTotal(paymentEx.getOrderTotal());
        // 设置各种费用
        Details details = new Details();
        // 商品总价
        details.setSubtotal(paymentEx.getSubTotal());
        // 税费
        details.setTax(paymentEx.getTax());
        amount.setDetails(details);

        transaction.setAmount(amount);

        ItemList itemList = new ItemList();
        /**
         * 收货地址
         */
        ShippingAddress shippingAddress = new ShippingAddress();

        shippingAddress.setRecipientName("安路");
        // 国家代码查询
        shippingAddress.setCountryCode("CN");
        shippingAddress.setState("china");
        shippingAddress.setCity("天津市");
        shippingAddress.setLine1("华明镇");
        shippingAddress.setPhone("18142219400");
        shippingAddress.setPostalCode("30000");

        itemList.setShippingAddress(shippingAddress);



        /**
         * 商品明细
         */
        List<ShopOrderItemEx> orderItemList = paymentEx.getOrderItemList();


        List<Item> items = new ArrayList<>();
        for (ShopOrderItemEx orderItemEx : orderItemList) {
            Item item = new Item();
            item.setSku(orderItemEx.getSku());
            item.setName(orderItemEx.getShortName());
            item.setPrice(orderItemEx.getPrise());
            item.setQuantity(orderItemEx.getQtyOrder());
            item.setCurrency(CURRENCY);
            items.add(item);
        }

        itemList.setItems(items);
        transaction.setItemList(itemList);

        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        /**
         * 支付信息
         */
        Payer payer = new Payer();
        payer.setPaymentMethod(PaypalPaymentMethod.paypal.toString());

        Payment payment = new Payment();
        payment.setIntent(PaypalPaymentIntent.sale.toString());
        payment.setPayer(payer);
        payment.setTransactions(transactions);

        /**
         * 回调地址
         */
        RedirectUrls redirectUrls = new RedirectUrls();
        redirectUrls.setReturnUrl(successUrl);
        redirectUrls.setCancelUrl(cancelUrl);
        payment.setRedirectUrls(redirectUrls);

        // 创建paypal API对象
        return payment.create(apiContext);

    }

    /**
     * 保存订单支付信息
     * @param shopOrderPayment
     * @return
     */
    public void savePayment(ShopOrderPayment shopOrderPayment) {

        System.out.println("保存订单数据成功");
        System.out.println("修改对应的订单状态");

        //更新订单的状态
        updateOrderStatus(shopOrderPayment.getOrderId(),1);
    }

    /**
     * 支付成功后更新订单状态和记录订单状态历史记录
     * @param orderId
     * @return
     */
    public void updateOrderStatus(Integer orderId, Integer orderStatus) {
        System.out.println("修改对应的订单状态");
        System.out.println("保存订单支付日志");
    }

    /**
     * 执行支付
     * @param paymentId
     * @param payerId
     * @return
     * @throws
     */
    public Payment executePayment(String paymentId, String payerId) throws Exception {
        // 创建paypal API对象
        Payment payment = new Payment();
        payment.setId(paymentId);
        PaymentExecution paymentExecute = new PaymentExecution();
        paymentExecute.setPayerId(payerId);
        return payment.execute(apiContext, paymentExecute);
    }


}
